import socket
import threading
from StaticClass import FormatData
from StaticClass import Communication
from StaticClass import Code
from hashlib import sha1
from time import sleep


class NetworkServer(threading.Thread):
    def __init__(self,copier):
        threading.Thread.__init__(self)
        self.copier = copier
        self.listcli = {}
        self.stop = False
        self.status = "disconnected"
    
    #Fonction thread
    def running(self):
        for thr in threading.enumerate():
            if thr == self:
                return True
        return False
    
    def run(self):
        print "thread server start"
        self.stop = True
        while self.stop == True:
            self.clientconnect = True
            try:
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.bind(('',self.copier.config.network['ServerPort']))
                self.socket.listen(5)
            except Exception as inst:
                self.status = "Error : "+inst[1]
                self.clientconnect = False
                self.copier.gui.error(inst[1])
            
            while self.stop == True and self.clientconnect == True:
                self.status = "connected"
                channel, details = self.socket.accept()
                thcli = ClientServer(self.copier,channel,details)
                self.listcli[thcli.getName()] = thcli
                thcli.start()
                print 'We have opened a connection with', details
            sleep(10)
        self.socket.close()
        print "thread server stopped"    
     
    def sendElement2All(self,element):
        for cli in  self.listcli:
            self.listcli[cli].sendElement(element) 
         
class ClientServer(threading.Thread):
    def __init__(self,copier,conn,details=None):
        threading.Thread.__init__(self)
        self.copier = copier
        self.connection = conn
        self.details = details
    
    def run(self):
        while True:
            data = self.receive()
            if not self.checkPassword(FormatData.Data2Str("password", data)):
                break
            elif FormatData.Data2Str("checkconnection", data) != None:
                self.send(FormatData.Str2Data("checkconnectionok", ""))
                break
            elif FormatData.Data2Str("quit", data) != None:
                break
            elif FormatData.Data2Str('request',data) != None:
                request = FormatData.Data2Str('request',data)
                if request == 'giveAll':
                    i = len(self.copier.list_element)-1
                    while i>=0:
                        self.sendElement(self.copier.list_element[i])
                        i-=1
                
        try:
            self.connection.close()
        except:
            pass      
        
        del self.copier.networkserver.listcli[self.getName()]
  
    def sendElement(self,element):
        self.send(FormatData.Str2Data('element', element))
        
    def send(self,data):
        print 'Serversend :'+data,self.details
        data = FormatData.Str2Data("data", Code.encode(self.copier.config.network['ServerPassword'], data))
        Communication.send(self.connection ,data)
        
    def receive(self):
        try:
            data = Communication.receive(self.connection)
            data = FormatData.Data2Str('data', data)
            return Code.decode(self.copier.config.network['ServerPassword'], data)
        except:
            return ''
    #function server
    def checkPassword(self,str):
        if str == sha1(self.copier.config.network['ServerPassword']).hexdigest():
            return True
        return False      
    
    